

package org.winexpress

import org.codehaus.groovy.grails.web.json.JSONObject;
import org.codehaus.groovy.grails.web.json.JSONArray;
import grails.converters.JSON

/**
 *
 * @author Swee Zhi
 */
class ProductTypeManagement {
    
    def listProductTypes() {
        def ProductTypes = ProductType.list()
        JSONArray arr = new JSONArray()
        ProductTypes.each() {
            JSONObject obj = new JSONObject()
            obj.put("id",it.id)
            obj.put("productTypeName",it.productTypeName)
            obj.put("description",it.description)
            arr.add(obj)
        }
        
        return arr
    }
    
    def getProductTypeByID(id) {
        def pt = ProductType.findById(id)
        JSONObject obj = new JSONObject()
        obj.put("id",pt.id)
        obj.put("productTypeName",pt.productTypeName)
        obj.put("description",pt.description)
        
        return obj
    }
    
    def getProductTypeByProductTypeName(productTypeName) {
        def pt = ProductType.findByProductTypeName(productTypeName)
        JSONObject obj = new JSONObject()
        obj.put("id",pt.id)
        obj.put("productTypeName",pt.productTypeName)
        obj.put("description",pt.description)
        obj.put("imageUrl",pt.imageUrl)
        
        return obj
    }
    
    def getProductTypeForDbByProductTypeName(productTypeName) {
        def pt = ProductType.findByProductTypeName(productTypeName)
        
        return pt
    }
    
    def addProductType(o) {
        def status
        
        ProductType pt = new ProductType()
        pt.productTypeName = o.get("productTypeName")
        if (o.get("description") == "") {
            pt.description = "-"
        }
        else {
            pt.description = o.get("description")
        }
        if (pt.save()) {
            status = true
        }
        else {
            status = false
        }        
        println 'Management >> Add Product Type >> ' + status
        
        return status
    }
    
    def updateProductType(productType) {
        def status
        
        ProductType pt = ProductType.findById(productType.id)
        if (productType.has("productTypeName")) { pt.productTypeName = productType.productTypeName }
        if (productType.has("description")) { pt.description = productType.description }
        if (pt.save(flush:true)) {
            status = true
        }
        else {
            status = false
        }        
        println 'Management >> Update Product Type >> ' + status
        
        return status
    }
    
    def deleteProductType(id) {
        def status
        
        ProductType pt = ProductType.findById(id)
        if (pt.delete()) {
            status = true
        }
        else {
            status = false
        }        
        println 'Management >> Delete Product Type >> ' + status
        
        return status
    }
}

